<script setup lang='ts'>
import { ref, reactive,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  GetAllUser,
  deleteUser,
  GetAllRoles,
  createUser,
  editUserInfo,
  resetUserPassword,
  addRoles,
  deleteRoles,
  editRoles,
  getAllPermission
} from '@/api/user'

defineProps({
  showRolesDialog: {
    type: Function,
    default: () => { }
  }
})

const defaultProps = {
  label: 'name',
  children: 'children'
}

// refs
const permissionTreeRef = ref()

// ruleForm
let ruleForm:any = reactive({
  isEditorFlag: '',
  menuIds: '',
  menuIdsisEditor: ''
})

// 选择的角色
let targetItem:any = reactive({})

// 权限列表
let permissionList:any = reactive({})

// 控制分配权限的弹框
const permissionVisible = ref(false)

// 选择的角色
const activeTitle = ref('')
// 角色的默认权限
const defaultCheckedKeys:any = ref([])

// 表格
const resultRoleList:any = ref([])
const roleList: any = ref([])

const cellStyle = {
  textAlign: 'center'
}

const headStyle = {
  textAlign: 'center'
}

// 分页
let pageInfo = reactive({
  total: 100,
  pageSize: 10,
  pageNum: 1
})

// 定义方法
onMounted(() => {
  getRoleList()
})
// 获取角色
const getRoleList = () => {
  GetAllRoles({
    MaxResultCount: 999
  }).then(({ result }) => {
    resultRoleList.value = result.items
    pageInfo.total = result.totalCount
    pageChange()
  })
}

// 页面跳转
const pageChange = (obj:any = { ...pageInfo }) => {
  pageInfo = { ...obj }
  roleList.value = []
  roleList.value = resultRoleList.value.slice(
    (obj.currentPage - 1) * obj.pageSize,
    obj.currentPage * obj.pageSize
  )
}

// 分配权限
const assignPermissions = async (row:any) => {
  // console.log(item);
  defaultCheckedKeys.value = await getActiveId([
    ...row.resourcePermissions,
    ...row.resourcePanels,
    ...row.resourcePanelItems
  ])
  targetItem = {}
  targetItem = { ...row }
  activeTitle.value = row.roleName
  let res = await getAllPermission()
  // let a =JSON.parse(JSON.stringify(result).replace(/name/g,"panelName").replace(/name/g,"itemName"))
  permissionList = formatPermissionList(res.result)

  permissionVisible.value = true
  activeTitle.value = row.roleName
  permissionVisible.value = true
}

// 权限数组格式化
const formatPermissionList = (arr:any) => {
  let list:any = []
  arr.forEach(el => {
    let { children, panelList, itemList } = el
    if (children && children.length > 0) {
      el.children = formatPermissionList([ ...children ])
    } else if (panelList && panelList.length > 0) {
      el.children = formatPermissionList([ ...panelList ])
    } else if (itemList && itemList.length > 0) {
      el.children = formatPermissionList([ ...itemList ])
    }
    el.name = el.name || el.panelName || el.itemName
    el.id = el.id.toString()
    list.push(el)
  })
  return list
}

// 获取所有权限id
const getActiveId = (arr:any) => {
  let list:any = []
  arr.forEach((el:any) => {
    list.push(el.id.toString())
  })
  return list
}

/*
      以下三个方法是在一定程度上区分el-tree的父子关系的
      防止子节点取消后父节点也取消
    */
const getCurrentNode = (data:any) => {
  let node = permissionTreeRef.value.getNode(data)
  childNodes(node)
  parentNodes(node)
  ruleForm.isEditorFlag = true
  ruleForm.menuIds = permissionTreeRef.value.getCheckedKeys()
  ruleForm.menuIdsisEditor = permissionTreeRef.value
    .getCheckedKeys()
    .concat(permissionTreeRef.value.getHalfCheckedKeys())
  console.log('object', ruleForm.menuIdsisEditor)

}
const childNodes = (node:any) => {
  let len = node.childNodes.length
  for (let i = 0; i < len; i++) {
    node.childNodes[i].checked = node.checked
    childNodes(node.childNodes[i])
  }
}
const parentNodes = (node:any) => {
  if (node.parent) {
    for (let key in node) {
      if (key === 'parent') {
        node[key].checked = true
        parentNodes(node[key])
      }
    }
  }
}

// 提交事件
const addPermission = () => {
  let activeIdList:any = [ ]
  permissionTreeRef.value.getCheckedKeys().forEach(item => {
    activeIdList.push({ id: item })
  })

  targetItem.permissions = [ ...activeIdList ]
  console.log(targetItem)
  editRoles({ ...targetItem }).then(() => {
    permissionVisible.value = false
    ElMessage({
      type: 'success',
      message: '保存成功!'
    })
    getRoleList()
  })
}

// 删除某项
const deleteItem = (row: any) => {
  console.log('删除的项')
}

const handlePlanSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handlePlanCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
</script>

<template>
  <el-table
    :cell-style="cellStyle"
    :header-cell-style="headStyle"
    :data="roleList"
    max-height="270"
  >
    <el-table-column
      prop="name"
      label="姓名"
    />
    <el-table-column
      prop="address"
      label="是否接受告警信息"
    />
    <el-table-column
      prop="address"
      label="备注"
    />
    <el-table-column
      prop="name"
      label="操作"
    >
      <template #default="scope">
        <div class="role-btn-box">
          <div
            class="update-btn"
            @click="showRolesDialog(1, scope.row)"
          >
            编辑
          </div>
          <div
            class="allocation-btn"
            @click="assignPermissions(scope.row)"
          >
            分配权限
          </div>
          <div
            class="delete-btn"
            @click="deleteItem(scope.row)"
          >
            删除
          </div>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination-box">
    <el-pagination
      v-model:current-page="pageInfo.pageNum"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
      @size-change="handlePlanSizeChange"
      @current-change="handlePlanCurrentChange"
    />
  </div>
  <el-dialog
    v-model="permissionVisible"
    width="50%"
    top="5%"
    :title="'角色:' + activeTitle"
    :close-on-click-modal="false"
  >
    <el-tree
      ref="permissionTreeRef"
      class="flow-tree"
      :data="permissionList"
      :props="defaultProps"
      node-key="id"
      :default-expand-all="true"
      :default-checked-keys="defaultCheckedKeys"
      :check-strictly="true"
      show-checkbox
      @check="getCurrentNode"
    />
    <div
      class="dialog-footer"
    >
      <el-button @click="permissionVisible = false;">
        取 消
      </el-button>
      <el-button
        type="primary"
        @click="addPermission"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang=scss>
.btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  >div {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 56px;
    height: 30px;
    color: #fff;
    border-radius: 5px;

    /* background-color: red; */

    &:hover {
      cursor: pointer;
    }
  }

  .resetting-btn {
    width: 92px;
    height: 30px;
    margin-left: 10px;
    background-color: #a6a9ad;
  }

  .update-btn {
    background-color: #e6a23c;
  }

  .delete-btn {
    margin-left: 10px;
    background-color: #f56c6c;
  }
}

.role-btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  >div {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 56px;
    height: 30px;
    color: #fff;
    border-radius: 5px;

    /* background-color: red; */

    &:hover {
      cursor: pointer;
    }
  }

  .allocation-btn {
    width: 92px;
    height: 30px;
    margin-left: 10px;
    background-color: #409eff;
  }

  .update-btn {
    background-color: #e6a23c;
  }

  .delete-btn {
    margin-left: 10px;
    background-color: #f56c6c;
  }
}

.pagination-box {
  margin-top: 10px;
}
</style>
